package com.weimei.conversionTreasure.activity;

import static com.mob.tools.utils.DH.SyncMtd.getPackageName;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.GridLayoutManager;

import android.app.Application;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.lxj.xpopup.XPopup;
import com.weimei.conversionTreasure.R;
import com.weimei.conversionTreasure.adapter.MarketAdapter;
import com.weimei.conversionTreasure.app.AppViewModelFactory;
import com.weimei.conversionTreasure.databinding.ActivityAddMarketBinding;
import com.weimei.conversionTreasure.http.entity.TabOneEntity;
import com.weimei.conversionTreasure.utils.ValidateUtils;
import com.weimei.conversionTreasure.viewModel.AddKhVM;
import com.weimei.conversionTreasure.viewModel.AddMarketVM;
import com.weimei.conversionTreasure.viewModel.MarketItemVM;
import com.weimei.conversionTreasure.weight.BottomTimePop;

import java.util.ArrayList;
import java.util.List;

import me.goldze.mvvmhabit.base.BaseActivity;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.tatarka.bindingcollectionadapter2.BR;

public class AddMarketActivity extends BaseActivity<ActivityAddMarketBinding, AddMarketVM> {

    private List<TabOneEntity> list = new ArrayList<>();

    MarketAdapter adapter;
    private int count = 0;
    private String type = "支出";
    private String className = "";
    String id="";

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_add_market;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void initParam() {
        super.initParam();
        id = getIntent().getStringExtra("id");
    }

    @Override
    public void initData() {
        super.initData();
        viewModel.setTitleText("添加交易");
        if (ValidateUtils.isNotEmptyString(id)){
            viewModel.id.set(id);
        }

        initView();

        getZCList();

        binding.tvZc.setOnClickListener(view -> {
            binding.tvZc.setBackgroundResource(R.drawable.rect_ff_12);
            binding.tvZc.setTextColor(Color.parseColor("#2B2E38"));

            binding.tvSy.setBackgroundColor(Color.parseColor("#f1f3f6"));
            binding.tvSy.setTextColor(Color.parseColor("#5A5D68"));
            getZCList();
            type = "支出";
        });

        binding.tvSy.setOnClickListener(view -> {
            binding.tvSy.setBackgroundResource(R.drawable.rect_ff_12);
            binding.tvSy.setTextColor(Color.parseColor("#2B2E38"));

            binding.tvZc.setBackgroundColor(Color.parseColor("#f1f3f6"));
            binding.tvZc.setTextColor(Color.parseColor("#5A5D68"));
            getSYList();
            type = "收益";
        });


    }




    public void getSYList( ) {
        list.clear();
        for (int i = 0; i < getResources().getStringArray(R.array.sy_str).length; i++) {
            TabOneEntity tabOneEntity = new TabOneEntity();
            tabOneEntity.ImgRes = getResources().getIdentifier("s_" + (i), "mipmap", getPackageName());
            tabOneEntity.tabStr = getResources().getStringArray(R.array.sy_str)[i];
            tabOneEntity.selImgRes = getResources().getIdentifier("s_" + (i)+"_s", "mipmap", getPackageName());
            list.add(tabOneEntity);
        }
        adapter = new MarketAdapter();
        adapter.addChildClickViewIds(R.id.item);
        GridLayoutManager layoutManager = new GridLayoutManager(this,5);
        binding.recyclerView.setLayoutManager(layoutManager);
        binding.recyclerView.setAdapter(adapter);

        adapter.setOnItemChildClickListener((adapter1, view, position) -> {
            adapter.setSel(position);
            className = list.get(position).tabStr;
        });
        adapter.setList(list);

    }

    public void getZCList( ) {
        list.clear();
        for (int i = 0; i < getResources().getStringArray(R.array.zc_str).length; i++) {
            TabOneEntity tabOneEntity = new TabOneEntity();
            tabOneEntity.ImgRes = getResources().getIdentifier("z_" + (i), "mipmap", getPackageName());
            tabOneEntity.selImgRes = getResources().getIdentifier("z_" + (i)+"_s", "mipmap", getPackageName());
            tabOneEntity.tabStr = getResources().getStringArray(R.array.zc_str)[i];
            list.add(tabOneEntity);
        }
        adapter = new MarketAdapter();
        adapter.addChildClickViewIds(R.id.item);
        GridLayoutManager layoutManager = new GridLayoutManager(this,5);
        binding.recyclerView.setLayoutManager(layoutManager);
        binding.recyclerView.setAdapter(adapter);

        adapter.setOnItemChildClickListener((adapter1, view, position) -> {
            adapter.setSel(position);
            className = list.get(position).tabStr;
        });
        adapter.setList(list);

    }

    @Override
    public AddMarketVM initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, (ViewModelProvider.Factory) factory).get(AddMarketVM.class);
    }

    private void initView() {
        binding.num1.setOnClickListener(v ->  binding.tvValue.setText(binding.tvValue.getText().toString() + "1"));
        binding.num2.setOnClickListener(v ->  binding.tvValue.setText(binding.tvValue.getText().toString() + "2"));
        binding.num3.setOnClickListener(v ->  binding.tvValue.setText(binding.tvValue.getText().toString() + "3"));
        binding.num4.setOnClickListener(v ->  binding.tvValue.setText(binding.tvValue.getText().toString() + "4"));
        binding.num5.setOnClickListener(v ->  binding.tvValue.setText(binding.tvValue.getText().toString() + "5"));
        binding.num6.setOnClickListener(v ->  binding.tvValue.setText(binding.tvValue.getText().toString() + "6"));
        binding.num7.setOnClickListener(v ->  binding.tvValue.setText(binding.tvValue.getText().toString() + "7"));
        binding.num8.setOnClickListener(v ->  binding.tvValue.setText(binding.tvValue.getText().toString() + "8"));
        binding.num9.setOnClickListener(v ->  binding.tvValue.setText(binding.tvValue.getText().toString() + "9"));
        binding.num0.setOnClickListener(v ->  binding.tvValue.setText(binding.tvValue.getText().toString() + "0"));
        binding.numPoint.setOnClickListener(v -> onSport());
        binding.llCurDate.setOnClickListener(v ->  {});
        //设置确定按钮被点击后，向外界提供监听
        binding.save.setOnClickListener(v -> {
            if (binding.tvValue.getText().equals("") || binding.tvValue.getText().equals("0")){
                ToastUtils.showShort("请输入金额");
                return;
            }else if (ValidateUtils.isEmptyString(className)){
                ToastUtils.showShort("请选择类别");
                return;
            }else {
                viewModel.saveData(type,
                        binding.tvValue.getText().toString(),
                        binding.edtMaker.getText().toString(),className);
            }
        });
        //设置取消按钮被点击后，向外界提供监听
        binding.del.setOnClickListener(v -> onDel());

        binding.llCurDate.setOnClickListener(v ->{
            new XPopup.Builder(AddMarketActivity.this)
                    .moveUpToKeyboard(false)//如果不加这个，评论弹窗会移动到软键盘上面
                    .enableDrag(true)
                    .asCustom(new BottomTimePop(AddMarketActivity.this, s1 -> {

                    },true,true))
                    .show();
        });
    }

    // 删除
    private void onDel() {
        String text = binding.tvValue.getText().toString();
        if (text.length() > 0) {
            if (text.endsWith(".")) {
                count = 0;
            }
            String newText = text.substring(0, text.length() - 1);
            //to delete the data contained in the brackets at once
            if (text.endsWith(")")) {
                char[] a = text.toCharArray();
                int pos = a.length - 2;
                int counter = 1;
                //to find the opening bracket position
                for (int i = a.length - 2; i >= 0; i--) {
                    if (a[i] == ')') {
                        counter++;
                    } else if (a[i] == '(') {
                        counter--;
                    }
                    //if decimal is deleted b/w brackets then count should be zero
                    else if (a[i] == '.') {
                        count = 0;
                    }
                    //if opening bracket pair for the last bracket is found
                    if (counter == 0) {
                        pos = i;
                        break;
                    }
                }
                newText = text.substring(0, pos);
            }
            //if e2 edit text contains only - sign or sqrt at last then clear the edit text e2
            if (newText.equals("-") || newText.endsWith("sqrt")) {
                newText = "";
            }
            //if pow sign is left at the last
            else if (newText.endsWith("^"))
                newText = newText.substring(0, newText.length() - 1);

            binding.tvValue.setText(newText);
        }
    }

    // 小数点
    public void onSport() {
        if (count == 0 &&  binding.tvValue.length() != 0) {
            binding.tvValue.setText( binding.tvValue.getText() + ".");
            count++;
        }
    }
}